package run.siyuan.handwriting.spring.v2.servlet;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import run.siyuan.handwriting.spring.v2.servlet.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dabai
 */
@Slf4j
public class SyDispatcherServlet extends HttpServlet {

    /**
     * 容器
     */
    private Map<String, Object> ioc = new ConcurrentHashMap<>();

    /**
     * 加载配置文件
     */
    private Properties configContext = new Properties();

    private Map<String, Object> handlerMapping = new ConcurrentHashMap<>();

    private List<String> classNames = new ArrayList<>(10);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {


        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        System.out.println(StrUtil.format("url:{} contextPath:{}", url, contextPath));
        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!");
            return;
        }

        //
        Method method = (Method) this.handlerMapping.get(url);
        // 方法形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 请求参数形参列表
        Map<String, String[]> params = req.getParameterMap();
        // 执行方法的形参列表
        Object[] paramValues = new Object[parameterTypes.length];

        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> aClass = parameterTypes[i];
            if (aClass.isAssignableFrom(HttpServletRequest.class)) {
                paramValues[i] = req;
                continue;
            }
            if (aClass.isAssignableFrom(HttpServletResponse.class)) {
                paramValues[i] = resp;
                continue;
            }
            if (aClass.isAssignableFrom(String.class)) {
                Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                for (int j = 0; j < parameterAnnotations.length; j++) {
                    for (Annotation parameterAnnotation : parameterAnnotations[j]) {
                        if (parameterAnnotation instanceof SYRequestParam) {
                            String paramName = ((SYRequestParam) parameterAnnotation).value();
                            if (!StrUtil.equals("", paramName)) {
                                String value = Arrays.toString(params.get(paramName)).replaceAll("\\[|\\]", "").replaceAll("\\s", "");
                                paramValues[i] = value;
                            }
                        }

                    }
                }
            }
        }

        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(this.ioc.get(beanName), paramValues);
    }

    /**
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置文件，获取包扫描路径
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        System.out.println(StrUtil.format("contextConfigLocation:{}", contextConfigLocation));
        doLoadConfig(contextConfigLocation);
        // 2. 根据包扫描路径，获取对应的class文件
        doScanner(configContext.getProperty("sy.component.scan"));

        // 3. 根据 class 文件进行初始化，并放入IOC 容器中
        doInstance();

        // 4. 完成依赖注入
        doAurowired();

        // 5. 根据对象进行依赖注入
        initHandlerMapper();

        System.out.println("SY Spring framework is init");
    }

    private void initHandlerMapper() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(SYController.class)) {
                continue;
            }
            StringBuilder baseUrl = new StringBuilder();
            // 判断当前类是否有 SYRequestMapping 注解
            if (clazz.isAnnotationPresent(SYRequestMapping.class)) {
                SYRequestMapping syRequestMapping = clazz.getAnnotation(SYRequestMapping.class);
                baseUrl.append(syRequestMapping.value());
            }
            for (Method method : clazz.getMethods()) {
                // 判断当前方法是否有 SYRequestMapping 注解
                if (!method.isAnnotationPresent(SYRequestMapping.class)) {
                    continue;
                }
                SYRequestMapping syRequestMapping = method.getAnnotation(SYRequestMapping.class);
                String url = syRequestMapping.value();
                baseUrl.append("").append(url.replaceAll("/+", "/"));
                System.out.println(StrUtil.format("baseUrl:{}", baseUrl));
                handlerMapping.put(baseUrl.toString(), method);
            }

        }
    }

    /**
     * 完成依赖注入
     */
    private void doAurowired() {
        for (Object clazz : ioc.values()) {
            Class<?> aClass = clazz.getClass();
            if (aClass.isAnnotationPresent(SYController.class)) {
                // 得到类的所有属性
                Field[] fields = aClass.getDeclaredFields();
                for (Field field : fields) {
                    if (!field.isAnnotationPresent(SYAutowired.class)) {
                        continue;
                    }
                    SYAutowired autowired = field.getAnnotation(SYAutowired.class);
                    String beanName = autowired.value();
                    if (StrUtil.equals("", beanName)) {
                        beanName = field.getType().getName();
                    }
                    field.setAccessible(true);

                    try {
                        // field.set('字段所在的类','要设置的新值')
                        field.set(clazz, ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }

            }

        }

    }

    /**
     * 根据包扫描到的类进行初始化
     */
    private void doInstance() {
        try {
            for (String className : classNames) {
                if (!className.contains(".")) {
                    continue;
                }
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(SYController.class)) {
                    Object instance = clazz.newInstance();

                    String beanName = toLowerFirstCase(clazz.getSimpleName());

                    ioc.put(beanName, instance);

                } else if (clazz.isAnnotationPresent(SYService.class)) {
                    SYService service = clazz.getAnnotation(SYService.class);
                    String beanName = service.value();
                    if ("".equals(beanName)) {
                        beanName = clazz.getName();
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (ioc.containsKey(i.getName())) {
                            throw new Exception("The " + i.getName() + " is exists!!!!");
                        }
                        ioc.put(i.getName(), instance);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载配置文件进行包扫描
     *
     * @param initParameter 配置文件路径
     */
    private void doLoadConfig(String initParameter) {
        InputStream is = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(initParameter);
            configContext.load(is);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("加载配置文件异常！！！");
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("关闭 InputStream 异常");
                }
            }
        }
    }

    /**
     * 进行包扫描
     *
     * @param scanPackage 包扫描路径
     */
    private void doScanner(String scanPackage) {

        String filePath = scanPackage.replaceAll("\\.", "/");
        URL url = this.getClass().getClassLoader().getResource(filePath);
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String clazzName = (scanPackage + "." + file.getName().replace(".class", ""));
                classNames.add(clazzName);
            }
        }
    }

    /**
     * 首字母小写
     *
     * @param className bean
     * @return String
     */
    private String toLowerFirstCase(String className) {
        char[] chars = className.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}